package com.sch.wanandroid.ui.my.coin

import android.animation.ValueAnimator
import android.os.Bundle
import android.view.View
import android.view.animation.DecelerateInterpolator
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.coder.zzq.smartshow.toast.SmartToast
import com.sch.wanandroid.R
import com.sch.wanandroid.adapter.CoinRecordAdapter
import com.sch.wanandroid.base.BaseActivity
import com.sch.wanandroid.constants.Constants
import com.sch.wanandroid.entity.CoinRecordBean
import kotlinx.android.synthetic.main.activity_coin.*
import kotlinx.android.synthetic.main.activity_coin.loadingTip
import kotlinx.android.synthetic.main.activity_coin.smartRefresh
import java.lang.Exception

/**
 * Created by Sch.
 * Date: 2020/4/26
 * description:积分页面
 */
class CoinActivity : BaseActivity() {
    private lateinit var coinViewModel: CoinViewModel

    private val coinRecordList by lazy { mutableListOf<CoinRecordBean>() }
    private val coinRecordAdapter by lazy { CoinRecordAdapter() }
    private var pageNum: Int = 1
    private var myCoin: Int = 0
    override fun init(savedInstanceState: Bundle?) {
        coinViewModel = ViewModelProvider(this).get(CoinViewModel::class.java)
        initTitle("我的积分")
        val bundle: Bundle? = intent.extras
        val coinStr = bundle?.getString(Constants.MY_COIN)
        coinStr?.let {
            try {
                myCoin = it.toInt()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = coinRecordAdapter
        recyclerView.overScrollMode = RecyclerView.OVER_SCROLL_NEVER
        initListener()
        loadingTip.loading()
        loadData()
        coinViewModel.coinRecordListLiveData.observe(this, Observer {
            setData(it)
        })
        coinViewModel.errorMsg.observe(this, Observer {
            onError(it)
        })
    }

    private fun loadData() {
        coinRecordList.clear()
        coinRecordAdapter.updata(coinRecordList)
        pageNum = 1
        coinViewModel.getCoinData(pageNum)
    }

    private fun initListener() {
        smartRefresh.setOnLoadMoreListener {
            pageNum++
            coinViewModel.getCoinData(pageNum)
        }
        // 设置无网络时重新加载点击事件
        loadingTip.setReloadListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
                loadingTip.loading()
                loadData()
            }
        })
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_coin
    }

    private fun setData(list: List<CoinRecordBean>) {
        dismissRefresh()
        startAnim()
        if (list.isNotEmpty()) {
            coinRecordList.addAll(list)
            coinRecordAdapter.updata(coinRecordList)
        } else {
            if (coinRecordList.size == 0) loadingTip.showEmpty()
            else SmartToast.info("没有更多数据了")
        }

    }

    private fun startAnim() {
        myCoin.let {
            val animator = ValueAnimator.ofInt(0, myCoin)
            animator.duration = 1500
            animator.interpolator = DecelerateInterpolator()
            animator.addUpdateListener {
                val currentValue = it.animatedValue as Int
                tvMyCoin.text = "$currentValue"
            }
            animator.start()
        }
    }

    fun onError(ex: String?) {
        //请求失败将page -1
        if (pageNum > 0) pageNum--
        dismissRefresh()
        if (coinRecordList.size == 0) {
            loadingTip.showInternetError()
        }
        SmartToast.error(ex)
    }

    /**
     * 隐藏刷新加载
     */
    private fun dismissRefresh() {
        loadingTip.dismiss()
        if (smartRefresh.state.isOpening) {
            smartRefresh.finishLoadMore()
            smartRefresh.finishRefresh()
        }
    }
}